<?php


namespace app\home\controller;


use app\admin\model\CityModel;
use app\utils\Response;

class CityController extends ApiBase
{
    /**
     * 获取省列表
     */
    public function getProvinceList()
    {
        $cityModel = new CityModel();
        $list = $cityModel->where([
            'level' => 1
        ])->field('cid,title')->select();
        Response::success([
            'list' => $list
        ]);
    }

    /**
     * 获取城市/区域列表
     */
    public function getChild()
    {
        $id = (int)$this->requestData['id'];
        if ($id <= 0) {
            Response::fail("id不能为空");
        }
        $cityModel = new CityModel();
        $list = $cityModel->where([
            'pid' => $id
        ])->field('cid,title')->select();
        if($list->isEmpty()){
            Response::fail("未找到数据");
        }
        Response::success([
            'list' => $list
        ]);
    }

    /**
     * 内部使用，把省市区的数据拆分成省、市、区
     */
    public static function getAllName($cityData = [])
    {
        $tmpArr = [];
        foreach ($cityData as &$city) {
            switch ($city['level']) {
                case 1:
                    $tmpArr['province_title'] = $city['title'];
                    break;
                case 2:
                    $tmpArr['city_title'] = $city['title'];
                    break;
                case 3:
                    $tmpArr['area_title'] = $city['title'];
                    break;
            }
        }
        return $tmpArr;
    }
}